package com.xlx.openLink.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xlx.openLink.base.*;
import com.xlx.openLink.conf.MysqlProperties;
import com.xlx.openLink.dao.AlarmMapper;
import com.xlx.openLink.dao.BackupMapper;
import com.xlx.openLink.dao.ManagerMapper;
import com.xlx.openLink.entity.pojo.Backup;
import com.xlx.openLink.entity.pojo.Manager;
import com.xlx.openLink.entity.pojo.Sys;
import com.xlx.openLink.enums.ResultCodeEnum;
import com.xlx.openLink.enums.SysParamsEnums;
import com.xlx.openLink.template.OpenLinkTemplate;
import com.xlx.openLink.uitls.AssertUtils;
import com.xlx.openLink.uitls.RemoteShellExecutor;
import com.xlx.openLink.vo.AlarmIds;
import com.xlx.openLink.vo.MysqlInfo;
import com.xlx.openLink.vo.RequestManagerLst;
import com.xlx.openLink.vo.SshVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ManagerService {

    @Autowired
    private ManagerMapper managerMapper;
    @Autowired
    private OpenLinkTemplate openLinkTemplate;
    @Autowired
    private MysqlProperties mysqlProperties;
    @Autowired
    private AlarmMapper alarmMapper;
    @Autowired
    private SysService sysService;
    @Autowired
    private BackupMapper backupMapper;


    /**
     * 登录操作
     *
     * @param manager
     * @return
     */
    @Transactional
    public Manager login(Manager manager, HttpServletRequest request) {
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager);
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager.getmName());
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager.getmPwd());
        manager.setmPwd(MD5Gen.getMD5(manager.getmPwd()));
        manager.setmLoginDate(new Date());
        manager.setmLoginIp(BaseUtils.getIpAddr(request));
        Manager ret = managerMapper.selectByNameAndPwd(manager);
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK, "用户不存在"), ret);
        manager.setmLoginDate(new Date());
        manager.setmPerIp(ret.getmLoginIp());//上次Ip地址
        manager.setmLoginDate(new Date());
        manager.setPkGuid(ret.getPkGuid());
        managerMapper.updateByPrimaryKeySelective(manager);
        ret.setmLoginIp(BaseUtils.getIpAddr(request));
        return ret;
    }

    /**
     * 更新操作
     *
     * @param manager
     * @return
     */
    @Transactional
    public int update(Manager manager) {

        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager);
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager.getPkGuid());
        return managerMapper.updateByPrimaryKey(manager);
    }


    /**
     * 添加操作
     *
     * @param manager
     * @return
     */
    @Transactional
    public int addManager(Manager manager) {
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager);
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager.getmName());
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager.getmPwd());
        manager.setmCreateDate(new Date());
        manager.setmPwd(MD5Gen.getMD5(manager.getmPwd()));
        manager.setPkGuid(BaseUtils.createGUID());
        return managerMapper.insertSelective(manager);
    }

    /**
     * 删除用户
     *
     * @param pkguid
     * @return
     */
    @Transactional
    public int delManager(String pkguid) {
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK, "主键为空"), pkguid);
        Manager manager = managerMapper.selectByPrimaryKey(pkguid);
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), manager);
        return managerMapper.deleteByPrimaryKey(pkguid);
    }

    public List<Manager> selectAll() {
        return managerMapper.selectAll();
    }


    public BasePage<Manager> listByPage(RequestManagerLst request) {
        AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK), request);
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<Manager> list = managerMapper.listByPage(request);
        PageInfo pageInfo = new PageInfo(list);
        return new BasePage<Manager>(pageInfo.getList(), pageInfo.getPageNum(), pageInfo.getPageSize(), pageInfo.getTotal());
    }

    public Manager select(String pkGuid) {
        return managerMapper.selectByPrimaryKey(pkGuid);
    }

    @Transactional
    public int delList(AlarmIds ids) {
        ids.getIds().forEach(e -> {
            alarmMapper.deleteByPrimaryKey(e);
        });
        return 1;
    }

    @Transactional
    public Backup backups() {
        Backup backup = new Backup();
        String fileName = mysqlProperties.getBackFileName() + "-" + DateUtils.formatDateTime2() + ".sql";
        try {
            File path = new File(mysqlProperties.getBackPath());
            if (!path.exists()) {// 如果目录不存在
                path.mkdirs();// 创建文件夹
            }
            File file = new File(mysqlProperties.getBackPath() + fileName);
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();

            Sys sys = sysService.selctByCode(SysParamsEnums.SYS_SSH.getCode());
            SshVo sshVo = (SshVo) JSONObject.parseObject(sys.getSysParam(), SshVo.class);
            AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK, "系统ssh参数是空请填写ssh信息"), sshVo);
            Sys mysqlSys = sysService.selctByCode(SysParamsEnums.MYSQL_INFO.getCode());
            MysqlInfo mysqlInfo = JSONObject.parseObject(mysqlSys.getSysParam(), MysqlInfo.class);
            AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK, "系统mysql参数是空请填写mysql信息"), mysqlSys);
            RemoteShellExecutor executor = new RemoteShellExecutor(sshVo.getIp(), sshVo.getName(), sshVo.getPwd(), sshVo.getPort());
            String stepOne = "mysqldump -u " + mysqlInfo.getuName() + " -p" + mysqlInfo.getPwd() + " -d " + " openlink > " + mysqlProperties.getBackPath()  + fileName;
            String stepTwo = "mysqldump -u " + mysqlInfo.getuName() + " -p" + mysqlInfo.getPwd() + " -t " + mysqlInfo.getDbName() + " --ignore-table=openlink.speed  >> " + mysqlProperties.getBackPath() + "/" + fileName;
            executor.exec(stepOne);
            executor.exec(stepTwo);
            backup.setBakCreateDate(new Date());
            backup.setBakPath(mysqlProperties.getBackPath() + fileName);
            backup.setPkGuid(BaseUtils.createGUID());
            backup.setBakName(fileName);
            backup.setBakUId("1111");
            backup.setBakUName("sys");
            backupMapper.insertSelective(backup);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ThreadRunTimeExcption(ResultCodeEnum.SYSTEM_FAILURE, "备份数据异常");
        }
        return backup;
    }

    /**
     * 恢复备份
     *
     * @param pkGuid
     */
    public void restore(String pkGuid) {
        try {
            Sys sys = sysService.selctByCode(SysParamsEnums.SYS_SSH.getCode());
            SshVo sshVo = (SshVo) JSONObject.parseObject(sys.getSysParam(), SshVo.class);
            AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK, "系统ssh参数是空请填写ssh信息"), sshVo);
            Sys mysqlSys = sysService.selctByCode(SysParamsEnums.MYSQL_INFO.getCode());
            MysqlInfo mysqlInfo = JSONObject.parseObject(mysqlSys.getSysParam(), MysqlInfo.class);
            AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK, "系统mysql参数是空请填写mysql信息"), mysqlSys);
            Backup backup = backupMapper.selectByPrimaryKey(pkGuid);
            AssertUtils.isNotNull(new ThreadRunTimeExcption(ResultCodeEnum.ILLEGAL_PARAM_BLANK, "备份信息不存在"), backup);
            RemoteShellExecutor executor = new RemoteShellExecutor(sshVo.getIp(), sshVo.getName(), sshVo.getPwd(), sshVo.getPort());
            executor.exec("mysql -u" + mysqlInfo.getuName() + " -p" + mysqlInfo.getPwd()  + " " + mysqlInfo.getDbName() + " < " + backup.getBakPath());
        } catch (Exception e) {

            throw new ThreadRunTimeExcption(ResultCodeEnum.SYSTEM_FAILURE, "数据恢复异常");
        }
    }


    public static void main(String[] args) {
        RemoteShellExecutor executor = new RemoteShellExecutor("222.140.4.13", "root", "lvbing147258..", 2212);
        try {
            executor.exec("  mysqldump -uroot -pMyNewPass4! -d openlink  > /var/local/openlink/sqlfile/a.sql");
            executor.exec("   mysqldump -uroot -pMyNewPass4! -t openlink --ignore-table=openlink.speed >> /var/local/openlink/sqlfile/a.sql");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
